export default {
  data () {
    return {
      currentItem: ''
    }
  },
  methods: {
    // reset
    clearDom () {
      document.querySelectorAll('.j_table_itm').forEach(itm => itm.remove())
    },
    monsedown (e, node) {
      this.clearDom()
      const createDom = document.createElement('div')
      createDom.className = 'u-draging j_table_itm'
      createDom.innerText = e.target.innerText
      const clientRect = e.target.getBoundingClientRect()
      createDom.style.minWidth = clientRect.width + 'px'
      this.offsetPos = {
        x: e.offsetX,
        y: e.offsetY
      }
      createDom.style.top = e.y - this.offsetPos.y + 'px'
      createDom.style.left = e.x - this.offsetPos.x + 'px'
      this.createDom = createDom
      this.currentItem = node
      document.body.appendChild(this.createDom)
      window.addEventListener('mousemove', this.mousemove)
      window.addEventListener('mouseup', this.mouseup)
    },
    mousemove (e) {
      if (!this.offsetPos) {
        return
      }
      this.createDom.style.left = e.x - this.offsetPos.x + 'px'
      this.createDom.style.top = e.y - this.offsetPos.y + 'px'
    },
    // 拖动放置元素
    mouseup (e) {
      this.offsetPos = null
      const to = document.querySelector('#j_container')
      const toClientRects = to.getClientRects()[0]
      if (e.clientX > toClientRects.x &&
        e.clientX < toClientRects.x + toClientRects.width &&
        e.clientY > toClientRects.y &&
        e.clientY < toClientRects.y + toClientRects.height) {
        this.$emit('add', {
          ...this.currentItem,
          left: e.clientX - toClientRects.x - e.offsetX,
          top: e.clientY - toClientRects.y - e.offsetY
        })
      }
      this.clearDom()
      window.removeEventListener('mousemove', this.mousemove, false)
      window.removeEventListener('mouseup', this.mouseup, false)
    }
  }
}